//
//  SearchResultTableViewController.m


#import "SearchResultTableViewController.h"
#import "SearchResultCellModel.h"
#import "DetailViewController.h"
#import "SearchTableViewCell.h"

@interface SearchResultTableViewController ()
{
    //存储搜索结果的数组
    NSMutableArray *_resultData;
}
@end

@implementation SearchResultTableViewController

//-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//       
//        
//    }
//    return self;
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化结果数组
    _resultData = [NSMutableArray new];
    //设置视图边缘
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    if (_searchStr != nil) {
        //异步搜索
        dispatch_queue_t takeMoneyQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(takeMoneyQueue, ^{[self searchFun];});
        
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _resultData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchResultCellModel *model =_resultData[indexPath.row];
    
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    
    cell.model = model;
    
    return cell;
}

#pragma mark - 搜索控制器发送搜索行为时执行的代理方法
//必须实现
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSLog(@"update");
}

#pragma mark - 搜索框代理
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //清空结果数组
    [_resultData removeAllObjects];
     _searchStr = searchBar.text;
    
    //每次输入保存入文件,在上一个页面中显示
    //调用代码块，并将自身作为参数传入
    
    self.transferBlock(self);
    
    [self searchFun];
    
}

-(void)searchFun
{
    //每次搜索数据都进行网络请求获取数据
    NSString *searchResult_rul_str = [NSString stringWithFormat:@"https://api.github.com/search/repositories?q=%@",_searchStr];
    NSURL *searchResult_rul = [NSURL URLWithString:searchResult_rul_str];
    NSData *searchResult_data = [NSData dataWithContentsOfURL:searchResult_rul];
    NSDictionary *searchResult_dic = [NSJSONSerialization JSONObjectWithData:searchResult_data options:0 error:nil];
    NSLog(@"%@",searchResult_dic);
    self.originalData = searchResult_dic[@"items"];
    NSLog(@"originalData:%@",self.originalData);
    
    //从原始数据中筛选符合的数据加入到结果中
    for (NSDictionary *adic in self.originalData) {
       
        
        NSData *aSearchDicData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",adic[@"url"]]]];
        
        NSDictionary *aSearchDic = [NSJSONSerialization JSONObjectWithData:aSearchDicData options:0 error:nil];
        
        SearchResultCellModel *model = [SearchResultCellModel allocInitFullName:adic[@"full_name"] aSearchDic:aSearchDic];
        
        [_resultData addObject: model];
    }
    //重新加载表视图
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    
    
    dispatch_async(mainQueue, ^{
        
        //更新UI
        [self.tableView reloadData];
    });
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
#pragma mark - 搜索控制器进入搜索状态时代理的方法
-(void)didPresentSearchController:(UISearchController *)searchController
{
    //清空结果数据,重新加载视图
    [_resultData removeAllObjects];
    [self.tableView reloadData];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    DetailViewController *dvc = segue.destinationViewController;
    SearchTableViewCell *cell = sender;
    dvc.dataDic = cell.dataDic;
//    NSLog(@"dvc.dataDic%@",dvc.dataDic);

}

-(void)viewWillAppear:(BOOL)animated
{
    //隐藏顶部
//    self.navigationController.navigationBarHidden = YES;
    
}

@end
